Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

/*
	wundAPI.js: JavaScript XPCOM component
	Uses Wunderground weather API to pull weather

	Programmed By: Basil Huffman (bahuffma@gwmail.gwu.edu)
*/

function wundAPI(){}

wundAPI.prototype = {
	classDescription: "Weather Underground API",
	classID:          Components.ID("{0d05a272-04fe-471b-83a8-da19aae2011f}"),
	contractID:       "@weather-forecaster/wundAPI;1",
	QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIwundAPI]),
	
	parseToJSON: function(text)
	{
		var input = JSON.parse(text);
		////
		try{
			var api_name = "Weather Underground";
			var city     = input.current_observation.display_location.city;
			var state    = input.current_observation.display_location.state;
			var zip      = input.current_observation.display_location.zip;
			var tempF    = input.current_observation.temp_f;
			var tempC    = input.current_observation.temp_c;
			var humidity = input.current_observation.relative_humidity;
			var weather  = input.current_observation.weather;
			var wind_mph = input.current_observation.wind_mph;
			var wind_kph = input.current_observation.wind_kph;
			////		
			var output = '{\n\t"api_name":"'+api_name+'",\n\t"city":"'+city;
			output += '",\n\t"state":"'+state+'",\n\t"zip":"'+zip;
			output += '",\n\t"tempF":"'+tempF+'",\n\t"tempC":"'+tempC;
			output += '",\n\t"humidity":"'+humidity+'",\n\t"weather":"'+weather;
			output += '",\n\t"wind_mph":"'+wind_mph+'",\n\t"wind_kph":"'+wind_kph;
			output += '"\n}';
			return output;
		}
		catch (anError)
		{
			var retval = "ERROR";
			return retval;		
		}
	},

	/*
		get weather, save as file, return file contents
		expectations:
			- url => sanitized string, built up by class code below
	*/
	getWeatherByUrl: function(url)
	{
		const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
		var request = XMLHttpRequest();
		
		request.open("GET",url,false);
		request.send(null);

		//if (this.extType == ".json")
			return this.parseToJSON(request.responseText);
		//else
		//	return this.parseXML(request.responseXML);
	},

	/*
		return the weather in a known format
		expectations:
			zip => 5 digit
	*/
	getWeatherByZipCode: function(zip) 
	{ 
		var url = "http://api.wunderground.com/api/e17115d7e24a448e/conditions/q/";
	
		//zip code lookups do not depend on state, so just add in the zip
		var zExt = zip + ".json";//this.extType;
		url += zExt;

		var retval = this.getWeatherByUrl(url);
		return retval;
	},

	isValidZip: function(zip)
	{
		var result = this.getWeatherByZipCode(zip);
		if (result == "ERROR")
			return false;

		return true;
	}
};

var components = [wundAPI];
if ("generateNSGetFactory" in XPCOMUtils)
  var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);  // Firefox 4.0 and higher
else
  var NSGetModule = XPCOMUtils.generateNSGetModule(components);    // Firefox 3.x
